import { defineStore } from 'pinia'
import { storage } from '@/utils/storage'
import type { IManagerData } from '@/types/permission/manager'
import type { CustomConfigListData } from '@/types/system/customConfig'
import defaultIcon from '@/assets/logo.svg'
const useUserStore = defineStore({
  id: 'user',
  state: () => ({
    user: {} as IManagerData,
    username: '你好！',
    token: '',
    logoConfig: {
      icon: '',
      logo: '',
      title: '',
      logo_shape: 1
    } as CustomConfigListData
  }),
  getters: {},
  actions: {
    setToken(token: string) {
      this.token = token
    },
    resetState() {
      this.$reset()
    },
    /**
     * 清除 Token
     */
    resetToken() {
      storage.remove('token')
      storage.remove('user')
    },
    /**
     *  注销
     */
    logout() {
      return new Promise((resolve) => {
        this.resetState()
        resolve(true)
      })
    },
    setConfigInfo(config: CustomConfigListData) {
      this.logoConfig = config
      console.log('this.logoConfig: ', this.logoConfig)
      this.setupLogo()
    },
    setupLogo() {
      // this.logoConfig.title = config?.title ?? ''
      // this.logoConfig.icon = config?.icon ?? ''
      // this.logoConfig.logo = config?.logo ?? ''
      // this.logoConfig.logo_shape = config?.logo_shape ?? 1

      if (this.logoConfig?.icon) {
        const link = document.querySelector('link[rel*="icon"]') || (document.createElement('link') as any)
        link.type = 'image/x-icon'
        link.rel = 'shortcut icon'
        link.href = this.logoConfig.status === 1 ? `${this.logoConfig.icon}` : defaultIcon
        console.log('link.href: ', link.href)
        document.getElementsByTagName('head')[0].appendChild(link)
      }
      if (this.logoConfig?.title) {
        const title = document.querySelector('title') || document.createElement('title')
        title.innerText = this.logoConfig.status === 1 ? `${this.logoConfig.title}` : 'CMS 管理系统'
        document.getElementsByTagName('head')[0].appendChild(title)
      }
    }
  },
  persist: {
    enabled: true,
    strategies: [{ storage: localStorage, paths: ['token', 'user', 'logoConfig'] }]
  }
})
export default useUserStore
